package pencil.controller;

import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import pencil.service.pencil_service;
import pencil.to.blackSimTO;
import pencil.to.factoryMaterial1TO;
import pencil.to.mixMachineTO;
import pencil.util.pencilUtil;


@Controller
@RequestMapping("/blackStick")
public class machineController{

	
	

	private pencil_service service;
	int runStep=0;
	private int  stratMeterialNum=0;
	public void setService(pencil_service service)throws SQLException{
		this.service= service;
	}
	
	
	@RequestMapping("/MixMachine.do")
	public ModelAndView mixMachine(String orderNumS) throws Exception{
		//0. 주문량에 필요한 재료계산
		System.out.println("뭐야 왜 실행한돼?");
		runStep=0;
		int orderNum=Integer.parseInt(orderNumS);
		
		System.out.println(orderNum);
		int product=0;//성공된 제품의수
		int abnormal=0;//비정상 품
		


		//1-1 세트의 분량 연필 1개
	
		while(product!=orderNum){//반복 주문량과 성공된 제품수와 같을 때까지
			//주문량 성공 실패
			
			//필요한 재료를 계산하여  DB에서 가져오는 값
			int bnNeed= 60*(orderNum-(product+abnormal));//개당 60씩 소모 필요량을 구하는 로직(주문량-생산품);
			int clayNeed= 60*(orderNum-(product+abnormal));//개당 60씩 소모 필요량을 구하는 로직(주문량-생산품);
			int waterNeed= 20;
			
			bnNeed=bnNeed +(abnormal*60);
			clayNeed=clayNeed+(abnormal*60);
			//1-2. 창고DB에서 재료값을 가지고 온다
			factoryMaterial1TO fto=service.getMeterial();
			factoryMaterial1TO ftoSet=new factoryMaterial1TO();	
			
			
			if(stratMeterialNum==0){/////////////////////////////////// udate Nullpoint Exception --- 발생 수정함
				if(fto!=null){
					stratMeterialNum=fto.getNo();
				}
			}
			
			int runSLevel= (int) pencilUtil.HolerunStep(orderNum);
			
			//2. 조건문 실행
			if(fto!=null){
				//창고에 값이 Null아니고   흑연과 점토의 비교값 크거나 같으면
				if(bnNeed <= fto.getBlackLead() && clayNeed<=fto.getClay()){
					//창고에서 출고 처리
					ftoSet.setBlackLead(fto.getBlackLead()-bnNeed);
					ftoSet.setClay(fto.getClay()-clayNeed);
					ftoSet.setDateRegist(pencilUtil.getNow());//현재날짜
					ftoSet.setInvenInfo("출고:흑연:"+bnNeed+" 점토:"+clayNeed);
					//출고한수 상황을 삽입
					service.insertSetMeterial(ftoSet);

					System.out.println("bnNeed:"+bnNeed);
					
					//로직 수행 값을 떨군다
					while(bnNeed!=0){
						//AJax 데이터 값 보내기
						if(runStep >= 100){	
							runStep=100;//진행률 리미트 지정
						}
						System.out.println("제품수:"+product+"--주문값"+orderNum);
						//재료감소
						bnNeed=bnNeed-60;
						clayNeed=clayNeed-60;
						waterNeed=waterNeed-20;
						System.out.println("bnNeed:"+bnNeed);
						//기계상태 조회
						mixMachineTO mmto = service.selectMixMachineInfo();
						if(mmto==null){
							mmto = new mixMachineTO(0, 0, 0, 0, "", "", 0, 0, "", 0, 0);//초기값 셋팅
							runStep=0;
						}
						mmto.setBlackRead(bnNeed+60); //자원 흑연-----창고 자원
						mmto.setClay(clayNeed+60);//점토----창고자원
						mmto.setWater(20);//물----창고자원이라 침
						mmto.setStartTime(pencilUtil.getNow());//시작시간
						
						//작동시간//
						Thread.sleep(1500);
						//
						
						int testValue=pencilUtil.troubleMaker(5, 5);//불량률 조절 매서드(기본값, 랜덤값)
							System.out.println("불량률:"+testValue);
						
						if(testValue>=7){//불량률 판별
							product=product+1;//성공품 증가
							mmto.setState("정상");//기계의 상태
							runStep=runStep+runSLevel;	
							if(runStep >= 100){	
								runStep=100;
							}	
						}else{
							//불량률 판단시 불량 부분
							abnormal=abnormal+1;
							factoryMaterial1TO fto1=service.getMeterial();//재고량을 불러와서
							fto1.setBlackLead(fto1.getBlackLead()+60);//불량난 60을 더해서 넣는다
							fto1.setClay(fto1.getClay()+60);
							fto1.setDateRegist(pencilUtil.getNow());
							fto1.setInvenInfo("재사용:흑연:60, 점토:60");
							//불량품 재사용을 위해 DB에 추가
							//DB----창고에 불량품을 넣는다
							service.insertSetMeterial(fto1);
							mmto.setState("불량");//기계의 상태	
						}	
							mmto.setAbnormal(abnormal);//비정상
							mmto.setEndTime(pencilUtil.getNow());//끝 시간
							mmto.setNormal(product);//정상품
							mmto.setMachineLife(mmto.getMachineLife()+1);//기계의 수명 +1 증가
							mmto.setRunstep(runStep);//진행률(성공품,주문량) 처리 메소드
						
							System.out.println("진행률:"+mmto.getRunstep());
							service.insertMixMachineInfo(mmto);
							System.out.println(mmto);
							Thread.sleep(1000);
					}//while		
				}else{
					//null값이 아닐때
					// DB의 재고량이 없어서 입고
					System.out.println("재고량이 부족합니다.");
					ftoSet.setBlackLead(bnNeed);//흑연필요량
					ftoSet.setClay(clayNeed);//점토필요량
					ftoSet.setDateRegist(pencilUtil.getNow());//현재날짜
					ftoSet.setInvenInfo("주문입고->흑연 :  +"+ftoSet.getBlackLead()+" 점토 : +"+ftoSet.getClay());
					service.insertSetMeterial(ftoSet);	
				}
			}else{
				//null 값 일때
				// DB의 재고량이 없어서 입고
				System.out.println("재고량이 없습니다.");
				ftoSet.setBlackLead(bnNeed);
				ftoSet.setClay(clayNeed);
				ftoSet.setDateRegist(pencilUtil.getNow());//현재날짜
				ftoSet.setInvenInfo("주문입고->흑연 :  +"+ftoSet.getBlackLead()+" 점토 : +"+ftoSet.getClay());
				//로직처리 믹스머신의 DB에 등
				service.insertSetMeterial(ftoSet);
			}
		}//while
		
		mixMachineTO immto= service.selectMixMachineInfo();
		System.out.println(immto);
		int su=immto.getNormal();
		System.out.println("입고될량: "+su);
		blackSimTO bsto=service.selectblackSim();
		if(bsto ==null){
			bsto= new blackSimTO(0, 0, "0", "0");
		}
		bsto.setAmount(bsto.getAmount()+su);
		System.out.println("입고 될 량"+bsto.getAmount());
		bsto.setDateRegist(pencilUtil.getNow());
		bsto.setInvenInfo("입고 : +"+immto.getNormal());
		service.insertblackSim(bsto);
		return null;
	}//mix
	
	@RequestMapping("/reportPage.do")
	public ModelAndView reportPage(HttpServletRequest request,HttpServletResponse response)throws Exception{
	
		 mixMachineTO mxmt=service.selectMixMachineInfo();
		HashMap map=new HashMap();
		
		int num=mxmt.getNormal()+mxmt.getAbnormal();
		System.out.println("num:    "+num);
		System.out.println(stratMeterialNum);
			ArrayList<mixMachineTO> list1=service.selectMixMachineInfoReport(num);/// 믹스 머신 테이블 검색
		
		ArrayList<factoryMaterial1TO>  list2= service.selectMeterialReport(stratMeterialNum);
		
		for(Object o : list1){
			System.out.println(o);
			}
		System.out.println(" -------------------------------------------------------");
		for(Object o : list2){
				System.out.println(o);
		}
		blackSimTO bsto=service.selectblackSim();
			map.put("list1", list1);
			map.put("list2", list2);
			map.put("bsto", bsto);
	 return new ModelAndView("/reportPage.jsp","reportX",map);
	}
	
	@RequestMapping("/getmoniter.do")
	public void bannerItem(HttpServletRequest request,HttpServletResponse response)throws Exception, NullPointerException{
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("cache-control", "no-cache");
		System.out.println("제이슨 호출");
		int orderNum=  Integer.parseInt((request.getParameter("orderNumS")));
		mixMachineTO mtto1= service.selectMixMachineInfo();
		mtto1.setRunstep(runStep);
		mtto1.setEndTime(pencilUtil.timeUsed(orderNum*3));
		String responseMsg =null;
		JSONObject jobj= new JSONObject(mtto1);
		responseMsg = jobj.toString();
		PrintWriter out = response.getWriter();
		System.out.println(responseMsg);
		out.print(responseMsg);
		return;
	}
	
	

		
	
	
}//class
